package com.heima.kafka.sample;

import org.apache.kafka.clients.producer.*;


import java.util.Properties;
import java.util.concurrent.ExecutionException;

/**
 * 生产者
 */
public class ProducerQuickStart {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        //1.创建kafka连接消息
        Properties properties = new Properties();
        //kafka连接地址
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,"192.168.200.130:9092");
        //key 喝 value 的序列化
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");

        //ack配置  消息确认机制
        properties.put(ProducerConfig.ACKS_CONFIG,"1");

        //重试次数 10次
        properties.put(ProducerConfig.RETRIES_CONFIG,10);

        //数据压缩
        properties.put(ProducerConfig.COMPRESSION_TYPE_CONFIG,"snappy");

        //2.创建生产者对象
        KafkaProducer<String, String> kafkaProducer = new KafkaProducer<String, String>(properties);

        //3.发送消息
        /**
         * 第一个参数：topic 主题
         * 第二个参数： key
         * 第三个参数： value
         */
        //同步发送消息
        ProducerRecord<String,String> kvProducerRecord = new ProducerRecord<String,String>("itcast-topic-out","key-001","hello kafka");
//        RecordMetadata recordMetadata = kafkaProducer.send(kvProducerRecord).get();
//        System.out.println(recordMetadata.offset());

        //异步发送消息
        kafkaProducer.send(kvProducerRecord, new Callback() {
            @Override
            public void onCompletion(RecordMetadata recordMetadata, Exception e) {
                if (e != null) {
                    System.out.println("记录异常信息到日志表中");
                }
                System.out.println(recordMetadata.offset());
            }
        });


        //4.关闭消息通道  必须要关闭，否则发送消息不成功
        kafkaProducer.close();

    }
}
